package cn.hdu.liang.core.web;

import cn.hdu.liang.common.web.session.SessionProvider;
import cn.hdu.liang.core.bean.user.Buyer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 处理上下文
 * 处理Session
 * 全局
 */
public class SpringmvcInterceptor implements HandlerInterceptor {

    @Autowired
    private SessionProvider sessionProvider;

    private static final String INTERCEPTOR_URL = "/buyer/";

    private Integer adminId;

    //方法前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if(adminId != null) {
            Buyer buyer = new Buyer();
            buyer.setUsername("fbb2014");
            sessionProvider.setAttribute(request, Constants.BUYER_SESSION, buyer);
        } else {
            Buyer buyer = (Buyer) sessionProvider.getAttribute(request, Constants.BUYER_SESSION);
            boolean flag = false;
            if(buyer != null) {
                flag = true;
            }
            request.setAttribute("isLogin", flag);
            //是否拦截
            String uri = request.getRequestURI();
            if(uri.startsWith(INTERCEPTOR_URL)) {
                //必须登录
                if(buyer == null) {
                    response.sendRedirect("/shopping/login.shtml?returnUrl=" + request.getParameter("returnUrl"));
                    return false;
                }
            }
        }
        return true;
    }

    //方法后
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    //页面渲染后
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    public void setAdminId(Integer adminId) {
        this.adminId = adminId;
    }
}
